#include <stdlib.h>

#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <time.h>

typedef  unsigned char      ub1;
typedef  unsigned short     ub2;
typedef  unsigned long      ub4;
typedef  unsigned long long ub8;

uint32_t hash32(uint32_t key)
{
	key += (key << 16);
	key ^= (key >> 17);
	key += (key << 4);
	key ^= (key >> 5);
	key += (key << 8);
	key ^= (key >> 13);
	return key;
}

uint32_t hash(const unsigned char* data, uint32_t len, uint32_t initval)
{
	int i;
	const uint8_t* orig = (const uint8_t*) data;
	const uint32_t* d = (const uint32_t*) data;
	int leftover = len % 4;
	int chunks = len / 4;
	uint32_t h = hash32(initval+1);
	for (i = 0; i < chunks; ++i) h = hash32(h ^ *d++);
	if (leftover == 0) return h;
	orig += len - leftover;
	uint32_t tmp = 0;
	switch (leftover) {
	case 3: tmp = *orig++;
	case 2: tmp = tmp << 8 + *orig++;
	case 1: tmp = tmp << 8 + *orig;
	}
	return hash32(tmp ^ h);
}

/*
 * The hash prefers little-endian architectures.  Here's my best guess
 * at whether you are little endian.  This hash could be rewritten to 
 * prefer big-endian architectures, but it would produce different
 * (equally strong) results.
 */


#define hashsize(n) ((ub4)1<<(n))
#define hashmask(n) (hashsize(n)-1)
#define rot(x,k) (((x)<<(k)) ^ ((x)>>(32-(k))))

/*
-------------------------------------------------------------------------------
mix -- mix 3 32-bit values reversibly.

This is reversible, so any information in (a,b,c) before mix() is
still in (a,b,c) after mix().

If four pairs of (a,b,c) inputs are run through mix(), or through
mix() in reverse, there are at least 32 bits of the output that
are sometimes the same for one pair and different for another pair.
This was tested for:
* pairs that differed by one bit, by two bits, in any combination
  of top bits of (a,b,c), or in any combination of bottom bits of
  (a,b,c).
* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
  is commonly produced by subtraction) look like a single 1-bit
  difference.
* the base values were pseudorandom, all zero but one bit set, or 
  all zero plus a counter that starts at zero.

Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
satisfy this are
    4  6  8 16 19  4
    9 15  3 18 27 15
   14  9  3  7 17  3
Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
for "differ" defined as + with a one-bit base and a two-bit delta.  I
used http://burtleburtle.net/bob/hash/avalanche.html to choose 
the operations, constants, and arrangements of the variables.

This does not achieve avalanche.  There are input bits of (a,b,c)
that fail to affect some output bits of (a,b,c), especially of a.  The
most thoroughly mixed value is c, but it doesn't really even achieve
avalanche in c.

This allows some parallelism.  Read-after-writes are good at doubling
the number of bits affected, so the goal of mixing pulls in the opposite
direction as the goal of parallelism.  I did what I could.  Rotates
seem to cost as much as shifts on every machine I could lay my hands
on, and rotates are much kinder to the top and bottom bits, so I used
rotates.
-------------------------------------------------------------------------------
*/
#define mix(a,b,c) \
{ \
  a -= c;  a ^= rot(c, 4);  c += b; \
  b -= a;  b ^= rot(a, 6);  a += c; \
  c -= b;  c ^= rot(b, 8);  b += a; \
  a -= c;  a ^= rot(c,16);  c += b; \
  b -= a;  b ^= rot(a,19);  a += c; \
  c -= b;  c ^= rot(b, 4);  b += a; \
}

/*
-------------------------------------------------------------------------------
final -- final mixing of 3 32-bit values (a,b,c) into c

Pairs of (a,b,c) values differing in only a few bits will usually
produce values of c that look totally different.  This was tested for
* pairs that differed by one bit, by two bits, in any combination
  of top bits of (a,b,c), or in any combination of bottom bits of
  (a,b,c).
* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
  is commonly produced by subtraction) look like a single 1-bit
  difference.
* the base values were pseudorandom, all zero but one bit set, or 
  all zero plus a counter that starts at zero.

This arrangement isn't very taxing.  Lots of constants work.
-------------------------------------------------------------------------------
*/
#define final(a,b,c) \
{ \
  c ^= b; c -= rot(b,14); \
  a ^= c; a -= rot(c,11); \
  b ^= a; b -= rot(a,25); \
  c ^= b; c -= rot(b,16); \
  a ^= c; a -= rot(c,4);  \
  b ^= a; b -= rot(a,14); \
  c ^= b; c -= rot(b,24); \
}

/*
-------------------------------------------------------------------------------
hash() -- hash a variable-length key into a 32-bit value
  k       : the key (the unaligned variable-length array of bytes)
  len     : the length of the key, counting by bytes
  initval : can be any 4-byte value
Returns a 32-bit value.  Every bit of the key affects every bit of
the return value.  Two keys differing by one or two bits will have
totally different hash values.

The best hash table sizes are powers of 2.  There is no need to do
mod a prime (mod is sooo slow!).  If you need less than 32 bits,
use a bitmask.  For example, if you need only 10 bits, do
  h = (h & hashmask(10));
In which case, the hash table should have hashsize(10) elements.

If you are hashing n strings (ub1 **)k, do it like this:
  for (i=0, h=0; i<n; ++i) h = hash( k[i], len[i], h);

By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
code any way you wish, private, educational, or commercial.  It's free.

Use for hash table lookup, or anything where one collision in 2^^32 is
acceptable.  Do NOT use for cryptographic purposes.
-------------------------------------------------------------------------------
*/

ub4 hashx(ub4 *key, size_t length, ub4 initval, ub4 *bb)
{
  ub4 a,b,c,len;

  /* Set up the internal state */
  len = (ub4)length;
  a = b = c = 0xdeadbeef + len + initval;

  if (LITTLE_ENDIAN && !((((ub1 *)key)-(ub1 *)0) & 0x3)) {
    ub4 *k32 = key;                                 /* read 32-bit chunks */
    ub1  *k8;

    /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
    while (len > 12)
    {
      a += *k32++;
      b += *k32++;
      c += *k32++;
      mix(a,b,c);
      len -= 12;
    }

    /*----------------------------- handle the last (probably partial) block */
    k8 = (ub1 *)k32;
    switch(len)
    {
    case 12: c+=k32[2]; b+=k32[1]; a+=k32[0]; break;
    case 11: c+=(((ub4)k8[10])<<16); /* fall through */
    case 10: c+=((ub2 *)k32)[4]; b+=k32[1]; a+=k32[0]; break;
    case 9 : c+=k8[8];                  /* fall through */
    case 8 : b+=k32[1]; a+=k32[0]; break;
    case 7 : b+=(((ub4)k8[6])<<16);  /* fall through */
    case 6 : b+=((ub2 *)k32)[2]; a+=k32[0]; break;
    case 5 : b+=k8[4];                  /* fall through */
    case 4 : a+=k32[0]; break;
    case 3 : a+=(((ub4)k8[2])<<16);  /* fall through */
    case 2 : a+=((ub2 *)k32)[0]; break;
    case 1 : a+=k8[0]; break;
    case 0 : return c;              /* zero length strings require no mixing */
    }

  } else if (LITTLE_ENDIAN && !((((ub1 *)key)-(ub1 *)0) & 0x1)) {
    ub2 *k16 = (ub2*)key;                                 /* read 16-bit chunks */
    ub1  *k8;

    /*--------------- all but last block: aligned reads and different mixing */
    while (len > 12)
    {
      a += k16[0] + (((ub4)k16[1])<<16);
      b += k16[2] + (((ub4)k16[3])<<16);
      c += k16[4] + (((ub4)k16[5])<<16);
      mix(a,b,c);
      k16 += 6; len -= 12;
    }

    /*----------------------------- handle the last (probably partial) block */
    k8 = (ub1 *)k16;
    switch(len)
    {
    case 12: c+=k16[4]+(((ub4)k16[5])<<16);
             b+=k16[2]+(((ub4)k16[3])<<16);
             a+=k16[0]+(((ub4)k16[1])<<16);
             break;
    case 11: c+=(((ub4)k8[10])<<16);  /* fall through */
    case 10: c+=k16[4];
             b+=k16[2]+(((ub4)k16[3])<<16);
             a+=k16[0]+(((ub4)k16[1])<<16);
             break;
    case 9 : c+=k8[8];                  /* fall through */
    case 8 : b+=k16[2]+(((ub4)k16[3])<<16);
             a+=k16[0]+(((ub4)k16[1])<<16);
             break;
    case 7 : b+=(((ub4)k8[6])<<16);  /* fall through */
    case 6 : b+=k16[2];
             a+=k16[0]+(((ub4)k16[1])<<16);
             break;
    case 5 : b+=k8[4];                  /* fall through */
    case 4 : a+=k16[0]+(((ub4)k16[1])<<16);
             break;
    case 3 : a+=(((ub4)k8[2])<<16);  /* fall through */
    case 2 : a+=k16[0];
             break;
    case 1 : a+=k8[0];
             break;
    case 0 : return c;                     /* zero length requires no mixing */
    }

  } else {                        /* need to read the key one byte at a time */
    ub1 *k = (ub1*) key;

    /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
    while (len > 12)
    {
      a += k[0];
      a += ((ub4)k[1])<<8;
      a += ((ub4)k[2])<<16;
      a += ((ub4)k[3])<<24;
      b += k[4];
      b += ((ub4)k[5])<<8;
      b += ((ub4)k[6])<<16;
      b += ((ub4)k[7])<<24;
      c += k[8];
      c += ((ub4)k[9])<<8;
      c += ((ub4)k[10])<<16;
      c += ((ub4)k[11])<<24;
      mix(a,b,c);
      k += 12; len -= 12;
    }

    /*-------------------------------- last block: affect all 32 bits of (c) */
    switch(len)                      /* all the case statements fall through */
    {
    case 12: c+=((ub4)k[11])<<24;
    case 11: c+=((ub4)k[10])<<16;
    case 10: c+=((ub4)k[9])<<8;
    case 9 : c+=k[8];
    case 8 : b+=((ub4)k[7])<<24;
    case 7 : b+=((ub4)k[6])<<16;
    case 6 : b+=((ub4)k[5])<<8;
    case 5 : b+=k[4];
    case 4 : a+=((ub4)k[3])<<24;
    case 3 : a+=((ub4)k[2])<<16;
    case 2 : a+=((ub4)k[1])<<8;
    case 1 : a+=k[0];
             break;
    case 0 : return c;
    }
  }

  final(a,b,c);
  *bb = b;
  return c;
}


#define BITS   8                 /* maximum number of bits set in the string */
#define BYTES  48                          /* length of the string, in bytes */
#define LARRAY 16                          /* 1<<LARRAY HLEN*ub4s per malloc */
#define LMMM   8                                    /* 1<<LMMM mallocs total */
#define HLEN   2                          /* length of a hash value, in ub4s */
#define ARRAY (((ub4)1)<<LARRAY)              /* length of a malloc, in ub4s */
#define MMM   (((ub4)1)<<LMMM)           /* number of segments in hash table */

struct mystate
{
 ub8    count;                            /* total number of strings tested */
 ub4    a[BITS];           /* a[i] says that q[a[i]] should be the ith word */
 ub4   *hash[MMM];                                  /* last such hash value */
 ub1   *string;                                      /* string to be hashed */
 ub4    x[4];                                      /* results from the hash */
 ub4    mask;                          /* what section of values to look at */
};
typedef  struct mystate  mystate;

void test(mystate *state)
{
 ub4  val;
 ub4  zip;
 ub4  off;
 ub4 *where;
 ub4 *x = state->x;
 ++state->count;

 /* report how much progress we have made */
 if (!(state->count & (state->count-1)))
 {
   int j;
   for (j=0; (((ub8)1)<<j) < state->count; ++j)
     ;
   printf("count 2^^%d\n", j);
 }

 /* compute a new hash value */
 x[0] = hash(state->string, BYTES, 0);

 /* look up where it belongs in the hash table */
 val = x[0];
 zip = ((val>>LMMM)&(ARRAY-1))*HLEN;
 off = (val)&(MMM-1);
 where = &state->hash[off][zip];

 /* did we actually get a collision? */
 if (where[0] == x[0]) {
   printf("collision!  %.8lx %.8lx %.8lx %.8lx  count %.8lx %.8lx\n",
          x[0], x[1], x[2], x[3],
          (ub4)(state->count>>32),
          (ub4)(state->count & 0xffffffff));
   exit(1);
 }

 /* store the current hash value */
 where[0] = x[0];
 where[1] = x[1];
}

void recurse(int depth, mystate *state)
{
 /* set my bit */
 state->string[state->a[depth]>>3] ^= (1<<(state->a[depth]&0x7));

 test(state);

 /* should we set some more bits? */
 if (depth+1 < BITS) {
   int newdepth = depth+1, i;
   for (i=state->a[depth]; i--;) {
     state->a[newdepth] = i;
     recurse(newdepth, state);
   }
 }

 /* clear my bit */
 state->string[state->a[depth]>>3] ^= (1<<(state->a[depth]&0x7));
}


void driver()
{
 mystate state;
 ub4    *a = state.a;
 ub1     s[BYTES];
 ub4     i, j;

 /* initialize the state */
 for (i=0; i<BYTES; ++i)
   s[i] = (ub1)0;
 state.string = s;
 state.count  = (ub8)0;

 /* allocate memory for the hash table */
 for (i=0; i<MMM; ++i) {
   state.hash[i] = (ub4 *)malloc(ARRAY*HLEN*sizeof(ub4));
   if (!state.hash[i])
     printf("could not malloc\n");
   for (j = 0; j < ARRAY; ++j)
     state.hash[i][j] = (ub4)0;                  /* zero out the hash table */
 }

 /* do the work */
 for (a[0] = 8*BYTES; a[0]--;)
   recurse(0, &state);

 /* free the hash table */
 for (i=0; i<MMM; ++i)
   free(state.hash[i]);
}


int main()
{
  driver();
}
